﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.IO;
using Dokan;
using System.Threading;
using DokanNetMirror;

namespace PeoneFS
{
    public class FileSystemService : InstallableServiceBase
    {
        const string _serviceName = "PeoneFS";
        const string _serviceDescription = "Pseudo Encrypted Offuscated File System";
        Thread mainThread;
        public FileSystemService() : base(_serviceName, _serviceDescription)
        {
            this.CanStop = true;
            this.CanPauseAndContinue = false;
            this.AutoLog = true;
        }

        protected override void OnStart(string[] args)
        {
            //base.RequestAdditionalTime(4000);
            mainThread = LaunchPeoneFS();
            base.OnStart(args);
        }

        public static Thread LaunchPeoneFS()
        {

            Thread runningThread = new Thread((o) =>
            {

                DokanOptions opt = new DokanOptions();
                opt.VolumeLabel = "PeoneFS";
                opt.DebugMode = false;
                opt.DriveLetter = Configuration.DriveLetter;
                opt.ThreadCount = 5;
                var fileSystem = new FileSystem(Configuration.Password);
                foreach (var folder in Configuration.MappedFolders)
                {
                    var result = fileSystem.AddMapping(folder.VirtualName, folder.RealName);
                    if (Environment.UserInteractive)
                    {
                        Console.WriteLine(result ?
                            "Mapped '{0}:\\{1}' --> '{2}" :
                            "Could not map '{0}:\\{1}' --> '{2}'. Does '{2}' exist?", 
                            opt.DriveLetter, 
                            folder.VirtualName,
                            folder.RealName
                            );
                    }
                }

                int res = DokanNet.DokanMain(opt, fileSystem);
            }
            );


            runningThread.Start();

            return runningThread;
        }

        protected override void OnStop()
        {
            DokanNet.DokanUnmount(Configuration.DriveLetter);
            mainThread.Abort();
            base.OnStop();
        }
    }
}
